<template>
  <div class="chart" ref="echartsRef"></div>
</template>
<script setup lang="ts">
  import * as echarts from 'echarts';
  import { onMounted, ref, markRaw, watch, defineExpose } from 'vue';
  let myChart = ref();
  const echartsRef = ref();
  const debounce = (method, delay) => {
    let timer: any = null;
    return function () {
      let context = this;
      let args = arguments;
      clearTimeout(timer);
      timer = setTimeout(function () {
        method.apply(context, args);
      }, delay);
    };
  };
  const props = defineProps({
    option: {
      type: Object,
      default: function () {
        return {};
      },
    },
    chartType: {
      type: String,
      default: '',
    },
  });
  watch(
    () => props.option,
    (newV) => {
      myChart.value.clear();
      myChart.value.setOption(newV, true);
    },
    { deep: true }
  );
  const init = () => {
    myChart.value = markRaw(echarts.init(echartsRef.value));
  };
  function screenAdpter() {
    myChart.value && myChart.value.resize();
  }
  onMounted(() => {
    init();
    window.addEventListener('resize', debounce(screenAdpter, 200));
  });
  defineExpose({ myChart });
</script>
<style scoped>
  .chart {
    width: 100%;
    height: 100%;
  }
</style>
